Vue.prototype.$message = ELEMENT.Message;
new Vue({
  el: "#app",
  data() {
    return {
      baseUrl: "/wycms-api",
      responseResult: "",
      loading: false, // 测试loading
      requestData: {
        url: "/channel/getChannelListForTree",
        method: "POST",
        headers: [
          {
            key: "Authorization",
            value:
              "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjJiMDM4OTkxLTQyNjMtNDZiMC1iZWNmLTcyZTZhMDQxY2E3YiJ9.AtTB2CdiOdKxYK8sd1e8QEwccGkTVNJvUkZzhC3Gaxw1ENm3D8O4QO2qaVC0ER_W0qJytaPkCVFIyj5XVyLB-g",
          },
          { key: "Content-Type", value: "application/x-www-form-urlencoded" },
        ],
        params: "siteId: 531",
        data: "",
      },
      duration: 1,
      requestsPerSecond: 1,
      interval: null,
    };
  },
  methods: {
    addHeader() {
      this.requestData.headers.push({ key: "", value: "" });
    },
    removeHeader(index) {
      this.requestData.headers.splice(index, 1);
    },
    /*
     * @params {number} 第n次调用接口
     */
    sendRequest(requestCount) {
      const { url, method, headers, params, data } = this.requestData;
      // const startTime = performance.now();
      return new Promise((resolve, reject) => {
        const startTime = performance.now();
        axios({
          url: this.baseUrl + url,
          method: method,
          headers: this.buildHeaders(headers),
          params: this.buildParams(params),
          data: data,
        })
          .then((response) => {
            // console.log(response);
            const endTime = performance.now();
            const responseTime = endTime - startTime;
            const result = {
              responseTime: responseTime,
              data: response.data,
              requestCount: requestCount,
            };
            resolve(result);
          })
          .catch((error) => {
            console.error(error);
            reject(error);
          });
      });
    },
    buildHeaders(headers) {
      const builtHeaders = {};
      for (const header of headers) {
        if (header.key && header.value) {
          builtHeaders[header.key] = header.value;
        }
      }
      return builtHeaders;
    },
    buildParams(params) {
      const builtParams = {};
      if (params) {
        const paramsArray = params.split("\n");
        for (const param of paramsArray) {
          const [key, value] = param.split(":");
          if (key && value) {
            builtParams[key.trim()] = value.trim();
          }
        }
      }
      return builtParams;
    },

    startTesting1() {
      const durationInMilliseconds = this.duration * 1000;
      const requestsPerSecond = this.requestsPerSecond;
      this.responseResult = "";
      this.interval = setInterval(() => {
        for (let i = 0; i < requestsPerSecond; i++) {
          this.sendRequest(i + 1);
        }
      }, 1000 / requestsPerSecond);
      setTimeout(() => {
        this.stopTesting();
      }, durationInMilliseconds);
    },
    startTesting() {
      this.loading = true;
      const durationInMilliseconds = this.duration * 1000;
      const requestsPerSecond = this.requestsPerSecond;
      this.responseResult = "";
      let requestCount = 0;
      let responseTimeSum = 0;
      let maxResponseTime = 0;
      let minResponseTime = Infinity;
      this.interval = setInterval(() => {
        console.log(
          "requestCount >= requestsPerSecond * this.duration: ",
          requestCount >= requestsPerSecond * this.duration,
          requestCount,
          requestsPerSecond,
          this.duration
        );

        if (requestCount >= requestsPerSecond * this.duration) {
          this.stopTesting();
          return;
        }

        const startTime = performance.now();
        requestCount++;
        this.sendRequest(requestCount)
          .then((response) => {
            const endTime = performance.now();
            const responseTime = (endTime - startTime).toFixed(2);
            responseTimeSum += Number(responseTime);
            maxResponseTime = Math.max(maxResponseTime, responseTime);
            minResponseTime = Math.min(minResponseTime, responseTime);
            console.log(response);
            // const contentLength = response.headers['content-length'];
            this.responseResult += `请求 ${response.requestCount}, 耗时：${responseTime}毫秒 \n`;
            // this.responseResult += `\n`;
            // this.responseResult += `返回结果大小：${contentLength}字节\n`;
            // this.responseResult += `返回结果：${JSON.stringify(response.data)}\n\n`;
            if (response.requestCount >= requestsPerSecond * this.duration)
              this.donePost(
                responseTimeSum,
                requestCount,
                maxResponseTime,
                minResponseTime
              );
          })
          .catch((error) => {
            console.error(error);
          });
      }, 1000 / requestsPerSecond);
      // setTimeout(() => {

      // }, durationInMilliseconds);
    },

    donePost(responseTimeSum, requestCount, maxResponseTime, minResponseTime) {
      this.responseResult += `接口测试完毕  \n`;

      const averageResponseTime =
        (responseTimeSum / requestCount).toFixed(2) - 0;
      this.responseResult += `总请求数量：${requestCount}\n`;
      this.responseResult += `平均响应时间：${averageResponseTime}毫秒\n`;
      this.responseResult += `最大响应时间：${maxResponseTime}毫秒\n`;
      this.responseResult += `最小响应时间：${minResponseTime}毫秒\n`;
    },
    stopTesting() {
      clearInterval(this.interval);
      this.loading = false;

      this.responseResult += `清空计时器  \n`;
    },
    getArticle() {
      this.requestData.url = "/article/list";
      this.requestData.params = `showType: 2 \n pageNum: 1 \n           pageSize: 10 \n channelId: 4821 \n `;
    },
    getChannel() {
      this.requestData.url = "/channel/getChannelListForTree";
      this.requestData.params = "siteId: 531";
    },

    //  const { url, method, headers, params, data } = this.requestData;
    // // const startTime = performance.now();
    // return new Promise((resolve, reject) => {
    //   const startTime = performance.now();
    //   axios({
    //     url: this.baseUrl + url,
    //     method: method,
    //     headers: this.buildHeaders(headers),
    //     params: this.buildParams(params),
    //     data: data,
    //   })
    handleCopy() {
      const { url, method, headers, params, data } = this.requestData;
      let str = `接口地址:${url} \n 方法:${method} \n 请求参数: \n params: ${JSON.stringify(
        this.buildParams(params)
      )} \n data:${data} \n 测试结果:${this.responseResult}
          `;
      this.handleCopyValue(str);
    },
    /**
     *
     * @param {string} text 复制的文本内容
     */
    handleCopyValue(text) {
      new Promise((res, rej) => {
        //浏览器禁用了非安全域的 navigator.clipboard 对象
        //在线上环境会报错 TypeError: Cannot read properties of undefined (reading 'writeText')
        if (!navigator.clipboard && window.isSecureContext) {
          res();
          return navigator.clipboard.writeText(text);
        } else {
          // 判断是否支持拷贝
          if (!document.execCommand("copy")) return Promise.reject();
          // 创建标签，并隐藏
          const textArea = document.createElement("textarea");
          textArea.style.position = "fixed";
          textArea.style.top = textArea.style.left = "-100vh";
          textArea.style.opacity = "0";
          textArea.value = text;
          document.body.appendChild(textArea);
          // 聚焦、复制
          textArea.focus();
          textArea.select();
          return new Promise((resolve, reject) => {
            // 不知为何，必须写这个三目，不然copy不上
            document.execCommand("copy") ? resolve() : reject();
            textArea.remove();
            res();
          });
        }
      })
        .then(() => {
          console.log("已复制到剪贴板");
          this.$message({
            message: text + "  已复制到剪贴板",
            type: "success",
          });
        })
        .catch(() => {
          this.$message({
            message: text + "  复制失败",
            type: "error",
          });
        });
    },
  },
});
